package me.xiaolei.float_window

import android.util.SparseArray
import android.view.View
import java.util.HashMap

/**
 * ViewHodel
 */
class ViewHolder constructor(val rootView: View) : AutoCloseable
{
    private val sp = SparseArray<View>()
    private val tags = HashMap<String, Any>()

    /**
     * 获取控件
     */
    fun <T : View> get(id: Int): T
    {
        val view = sp[id] ?: rootView.findViewById(id)
        sp.put(id, view)
        return view as T
    }

    /**
     * 获取暂存的目标
     */
    fun <T : Any> getTarget(key: String): T?
    {
        return tags[key] as? T?
    }

    /**
     * 获取暂存的目标
     */
    fun <T : Any> getTarget(key: String, def: T): T
    {
        val value = tags[key] as? T?
        return value ?: def
    }

    /**
     * 设置暂存的目标
     */
    fun setTarget(key: String, value: Any)
    {
        tags[key] = value
    }

    override fun close()
    {
        sp.clear()
        tags.clear()
    }
}